import cv2
from flask import Flask, render_template, Response, request
import threading
import socket
import time
import numpy as np

global pause_all_flag
pause_all_flag = 0
global kill_all_flag
kill_all_flag = 0

global command_str
command_str = None
    
local_post = 1212
while True:
    try:
        web_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        web_socket.connect(("8.8.8.8",80))
        local_ip = str(web_socket.getsockname()[0])
        web_socket.close()
        print("Network Enable")
        break
    except:
        print("Network Error...")
        time.sleep(5)

web_app = Flask(__name__)

global last_time
last_time = time.time()
def get_img():
    global last_time
    now_today = time.time()
    fps = now_today-last_time
    try:
        fps = str(int(1/fps))
    except:
        fps = "Infinite"
    img = np.full((480, 640, 3), 255, dtype=np.uint8)

    # 获取带毫秒的时间戳
    
    milliseconds = int((now_today - int(now_today)) * 1000)
    time_hour = time.localtime(now_today).tm_hour
    time_min = time.localtime(now_today).tm_min
    time_sec = time.localtime(now_today).tm_sec  # 新增秒数

    if time_hour < 10:
        time_hour = "0"+str(time_hour)
    if time_min < 10:
        time_min = "0"+str(time_min)
    local_time_str = f"{time.localtime(now_today).tm_year}-{time.localtime(now_today).tm_mon:02d}-{time.localtime(now_today).tm_mday:02d} " \
                f"{time_hour:02d}:{time_min:02d}:{time_sec:02d}.{milliseconds:03d}"  # 添加秒和毫秒
    local_time_str = local_time_str + " FPS:" + fps
    # 在图像上绘制时间戳
    cv2.putText(img, local_time_str, 
        (10, 470),  # 左下角位置
        cv2.FONT_HERSHEY_SIMPLEX, 
        1,  # 字体大小
        (0, 0, 0),  # 黑色字体
        2)  # 线宽
    last_time = now_today
    return img

global cam_img
try:
    cam_img = get_img()
    high=cam_img.shape[0]
    width=cam_img.shape[1]
except:
    pause_all_flag = 1
    kill_all_flag = 1


def command_jugg():
    global kill_all_flag
    global pause_all_flag
    global command_str
   
    print(command_str)
    command_str = None
    
@web_app.route('/', methods=['GET', 'POST'])
def index():  
    global kill_all_flag
    global pause_all_flag
    global command_str
    
    if request.method == 'POST':
        command_str = str(request.form.get('WEB_COMMAND'))
        
        if kill_all_flag == 0 and pause_all_flag == 0:
            command_jugg()
        elif kill_all_flag == 0 and pause_all_flag == 1:
            print(command_str)
            if command_str == "继续程序":
                pause_all_flag = 0
                print("Continue")
            else:
                print("程序已暂停，继续请按键")
        else:
            print("程序已终止，请重启程序")
            
    now_today = time.time()
    time_hour = time.localtime(now_today).tm_hour
    time_min = time.localtime(now_today).tm_min
        
    if time_hour < 10:
        time_hour = "0"+str(time_hour)
    if time_min < 10:
        time_min = "0"+str(time_min)
    local_time_str = str(time.localtime(now_today).tm_year)+"-"+str(time.localtime(now_today).tm_mon)+"-"+str(time.localtime(now_today).tm_mday)+" "+str(time_hour)+":"+str(time_min)
                
    data = {
        '当前时间：': [ local_time_str]
        }
        
    return render_template('index.html',data_dict=data)


def img_main():
    global pause_all_flag
    global kill_all_flag
    global cam_img 
    
    while True:
        time.sleep(0.1)
        while pause_all_flag==0:
            cam_img = get_img()
            # cv2.imshow("http://"+local_ip+":"+str(local_post)+"/ (img: video_feed)",cam_img)
            # 展示图像            
            if pause_all_flag == 1:
                pause_all_flag = 1
                print("暂停程序")
                cv2.destroyAllWindows()
                break
            # if cv2.waitKey(10) == 27:   # 通过esc键退出摄像
            #     kill_all_flag = 1
            #     pause_all_flag = 1
            #     print("结束程序")
            #     cv2.destroyAllWindows()
            #     break
        if kill_all_flag == 1:
            break

    print("全部退出")
    return 

def send_img():
    global cam_img
    global pause_all_flag
    while pause_all_flag == 0:
        image = cv2.imencode('.jpg', cam_img)[1].tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + image + b'\r\n')
        if pause_all_flag == 1:
            break
    return 


@web_app.route('/video_feed')
def video_feed():
    return Response(send_img(), mimetype='multipart/x-mixed-replace; boundary=frame')

def start_server():
    web_app.run(host='0.0.0.0', port=local_post)

def main():
    thread_send = threading.Thread(target=start_server)
    thread_send.setDaemon(True)
    thread_send.start() 
    
    img_main()
    
    time.sleep(1)
    print("已退出所有程序")
    return 

if __name__ == "__main__":    
    main()
    